package com.ts.enterprise.module.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ts.enterprise.common.interceptor.AuthInterceptor;
import com.ts.enterprise.common.query.LoginUser;
import com.ts.enterprise.enums.StatusEnum;
import com.ts.enterprise.exception.check.ResultNoExistException;
import com.ts.enterprise.module.user.dao.WorkerDao;
import com.ts.enterprise.module.user.entity.Dict;
import com.ts.enterprise.module.user.entity.Worker;
import com.ts.enterprise.module.user.entity.WorkerInfo;
import com.ts.enterprise.module.user.entity.WorkerTag;
import com.ts.enterprise.module.user.mapper.WorkerInfoMapper;
import com.ts.enterprise.module.user.query.WorkerTagUpdateQueryDTO;
import com.ts.enterprise.module.user.query.update.WorkerInfoUpdateQuery;
import com.ts.enterprise.module.user.query.update.WorkerTagUpdateQuery;
import com.ts.enterprise.module.user.vo.WorkerDetailVO;
import com.ts.enterprise.module.user.vo.WorkerTagSortVO;
import com.ts.enterprise.module.user.vo.WorkerTagVO;
import com.ts.enterprise.module.user.vo.WorkerShowSkillVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dean
 * @since 2021-10-18
 */
@Service
public class WorkerInfoService extends ServiceImpl<WorkerInfoMapper, WorkerInfo> {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private WorkerInfoMapper workerInfoMapper;

    @Autowired
    private WorkerDao workerDao;

    @Autowired
    private WorkerTagService workerTagService;

    @Autowired
    private WorkerService workerService;

    public Object getDetailById() {
        WorkerDetailVO vo = new WorkerDetailVO();
        LoginUser loginUser = AuthInterceptor.user.get();
        Worker worker = workerService.getById(loginUser.getId());
        Optional.ofNullable(worker).orElseThrow(ResultNoExistException::new);
        WorkerInfo workerInfo = getByWorkerId(worker.getId());
        Optional.ofNullable(workerInfo).orElseThrow(ResultNoExistException::new);
        List<WorkerTagVO> tagVOS = workerInfoMapper.listWorkTagByWorkerId(worker.getId(),Arrays.asList(1, 2));
        Map<String, Object> map = new HashMap<>();
        map.put("showSkills", getShowSkillListByWorkerId(worker.getId()));
        map.put("tagVOS", tagVOS);
        map.put("workerInfo", workerInfo);
        map.put("tagStatus", workerInfo.getTagStatus());
        map.put("workerInfoStatus", workerInfo.getInfoStatus());
        map.put("username", worker.getUsername());
        map.put("age", worker.getAge());
        map.put("isFree", workerInfo.getIsFree());
        map.put("starLevel", "五星保姆");
        return map;
    }

    public Object getShowSkillListByWorkerId(Integer workerId) {
        List<WorkerTagSortVO> workerTagSort = workerInfoMapper.listWorkSortTagByWorkerId(workerId, Arrays.asList(3));
        List<WorkerTagVO> workerTagVOS = workerInfoMapper.listWorkTagByWorkerId(workerId, Arrays.asList(3));
        Map<Integer, List<WorkerTagVO>> collect = workerTagVOS.stream()
                .collect(Collectors.groupingBy(WorkerTagVO::getTagId));
        for (WorkerTagSortVO vo : workerTagSort) {
            vo.setStatus(1);
            List<WorkerTagVO> vos = collect.get(vo.getTagId());
            if (CollectionUtils.isNotEmpty(vos)){
                long count = vos.stream().filter(s -> s.getStatus().equals(StatusEnum.wait.getCode())).count();
                if (count>0){
                    vo.setStatus(StatusEnum.wait.getCode());
                }
                long count1 = vos.stream().filter(s -> s.getStatus().equals(StatusEnum.reject.getCode())).count();
                if (count1>0){
                    vo.setStatus(StatusEnum.reject.getCode());
                }
                vos.stream().sorted(Comparator.comparing(WorkerTagVO::getId));
            }
            vo.setWorkerTagVOList(vos);
        }
        return workerTagSort;
    }

    public WorkerInfo getByWorkerId(Integer workerId) {
        return super.getOne(new LambdaQueryWrapper<WorkerInfo>().eq(WorkerInfo::getWorkerId, workerId));
    }

    public synchronized WorkerInfo saveInit(Integer workerId) {
        WorkerInfo build = WorkerInfo.builder().workerId(workerId).createTime(new Date()).build();
        super.save(build);
        return build;
    }

    public Object updateInfo(WorkerInfoUpdateQuery query) {
        LoginUser loginUser = AuthInterceptor.user.get();
        Integer id = loginUser.getId();
        WorkerInfo info = getByWorkerId(id);
        WorkerInfoUpdateQuery updateQuery = new WorkerInfoUpdateQuery();
        BeanUtils.copyProperties(info, updateQuery);
        if (!query.equals(updateQuery)){
            WorkerInfo workerInfo = new WorkerInfo();
            BeanUtils.copyProperties(query, workerInfo);
            workerInfo.setUpdateTime(new Date());
            workerInfo.setInfoStatus(0);
            super.updateById(workerInfo);
        }
        return true;
    }

    public Object updateWorkTag(WorkerTagUpdateQueryDTO query) {
        LoginUser loginUser = AuthInterceptor.user.get();
        Integer id = loginUser.getId();
        List<WorkerTagUpdateQuery> list = query.getWorkerTagUpdateList();
        List<WorkerTag> allList = workerTagService.listByWorkId(id);
        List<WorkerTagUpdateQuery> tagUpdateQueries = list.stream().filter(s -> null != s.getId()).collect(Collectors.toList());
        List<WorkerTagUpdateQuery> tagSaveQueries = list.stream().filter(s -> null == s.getId()).collect(Collectors.toList());
        List<WorkerTag> saveList = new ArrayList<>();
        Date date = new Date();
        if (CollectionUtils.isNotEmpty(tagSaveQueries)){
            tagSaveQueries.stream().forEach(s->{
                WorkerTag workerTag = new WorkerTag();
                BeanUtils.copyProperties(s, workerTag);
                workerTag.setStatus(StatusEnum.wait.getCode());
                workerTag.setCreateTime(date);
                saveList.add(workerTag);
            });
        }
        List<WorkerTag> updateList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tagUpdateQueries)){
            for (WorkerTagUpdateQuery workerTag : tagUpdateQueries) {
                WorkerTagUpdateQuery oldQuery = new WorkerTagUpdateQuery();
                if (CollectionUtils.isNotEmpty(allList)){
                    List<WorkerTag> collect = allList.stream().filter(s -> s.getId().equals(workerTag.getId())).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(collect)){
                        WorkerTag tag = collect.get(0);
                        BeanUtils.copyProperties(tag, oldQuery);
                        if (!oldQuery.equals(workerTag)){
                            WorkerTag tag1 = new WorkerTag();
                            BeanUtils.copyProperties(workerTag, tag1);
                            tag1.setStatus(StatusEnum.wait.getCode());
                            tag1.setUpdateTime(date);
                            updateList.add(tag1);
                        }
                    }
                }
            }
        }
        workerDao.saveLock(saveList, updateList);
        return true;
    }
}
